import random
import time
import re

import requests

from decrypt import decrypt


while 1:
    listid = '4396924'
    brandid = '1902857'
    idnum = brandid + listid
    zheng = ''
    idlength = 20 - len(idnum)

    for _ in range(idlength):
        zheng += str(round(random.random() * 9))

    rnd = f'{brandid}{listid}{zheng}'

    captcha_url = f'https://v.tiantianvote.com/api/c2/captchas.png.php?rnd={rnd}&type=2&id={listid}'

    # time.sleep(1)
    resp = requests.get(captcha_url, timeout=10)
    # print(resp.ok)
    with open('vote.jpg', 'wb') as f:
        f.write(resp.content)

    resp = requests.post("http://127.0.0.1:7788", data=resp.content)
    code = resp.json()["code"]


    # captcha = input('输入验证码')

    captcha = (decrypt(code)).strip()

    data = {
        'captcha': captcha,
        'rnd': rnd,
        'type': 2,
        'id': listid,
    }
    time.sleep(1)
    resp = requests.post('https://v.tiantianvote.com/api/c2/captchas.check1.php', data=data, timeout=10)
    print(resp.text)
    if re.search('﻿{"status":200,', resp.text):
        # print(captcha)
        break
    else:
        # time.sleep(random.randint(10, 60) * random.random())
        continue

data = {
    'brandid': brandid,
    'itemid': listid,
    'yqm': captcha,
    'rnd': rnd,
    'token': 'cbd9e9502c3fffd6605f579480f58ce2',
    'ouid': '37754235',
    'sid': '0cf703fcd4add7d4',
}
time.sleep(1)

headers_p = {
    'Host': 'v.tiantianvote.com',
    'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
    'Origin': 'https://h5.zhiyyuan.cn',
    'Accept': 'application/json, text/javascript, */*; q=0.01',
    'User-Agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 13_6_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148 MicroMessenger/7.0.15(0x17000f2b) NetType/WIFI Language/zh_CN',
    'Referer': 'https://h5.zhiyyuan.cn/m.php?v=0cf703fcd4add7d4&id=115&sign=friend&from=groupmessage&id=70&sign=friend&id=107&sign=friend',
    'Accept-Language': 'zh-cn',
}

resp = requests.post('https://v.tiantianvote.com/v.php', data=data, headers=headers_p, timeout=10)
print(resp.text)
# if re.search('"code":1,"msg":"success"', resp.text):
#     redis_cli.sadd('success_uid', uid)
#     redis_cli.set(uid, 1, ex=1800)
